package marmalius.command;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import marmalius.Player;
import marmalius.command.admin.*;
import marmalius.tools.DBService;
import marmalius.tools.LogService;

public class CommandService {
	private static final CommandService instance = new CommandService();
	private Map<String, BaseCommand> commands;
	
	public CommandService() {
		commands = new HashMap<String, BaseCommand>();
		
		commands.put("additem", new AddItem());
		commands.put("addcoin", new AddCoin());
		commands.put("reload", new Reload());
		commands.put("spawn", new Spawn());
		commands.put("tele", new Tele());
		
		commands.put("test", new Test());
		
		loadCommand();
	}
	
	public void loadCommand() {
		try {
			ResultSet rs = DBService.getInstance().doQuery("SELECT * FROM command");
			while (rs.next()) {
	    		BaseCommand load = commands.get(rs.getString("name"));
	        	if (load != null) {
	        		load.setSecurity(rs.getInt("security"));
	        		load.setHelp(rs.getString("help"));
	        	}
	        	else
	        		LogService.getInstance().logError("Command " + rs.getString("name") + " not found.");
			}
			rs.close();
		}
		catch (SQLException ex) {
			LogService.getInstance().logError("Can't load Command");
		}
	}
	
	public void process(Player player, String command) {
		String[] cmd = command.split(" ");
		if (cmd.length == 0)
			return ;
		BaseCommand myCommand = commands.get(cmd[0]);
		if (myCommand != null) {
			if (myCommand.haveAccess(player.GetPlayerRights()))
				myCommand.process(player, firstRemove(cmd, 1));
			else
				player.sendPlayerMessage("Command not found : "+cmd[0]);
		}
		else
			player.sendPlayerMessage("Command not found : "+cmd[0]);
	}
	
	public static CommandService getInstance() {
		return instance;
	}
	
	private static String[] firstRemove(String[] params, int needToRemove) {
		int newMax = params.length - needToRemove;
		if (newMax <= 0)
			return null;
		String [] newParams = new String[newMax];
		
		for (int i = 0; i < newMax; i++)
			newParams[i] = params[i+needToRemove];
		
		return newParams;
	}
}
